package com.canbot.u05.activity.attendance;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.button.MaterialButton;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.canbot.u05.R;
import com.canbot.u05.activity.BaseActivityNoTitle;
import com.canbot.u05.bean.AttendanceSettings;
import com.canbot.u05.bean.KqGroup;
import com.canbot.u05.socket.MsgSendUtils;
import com.canbot.u05.socket.MsgType;
import com.canbot.u05.utils.Logger;
import com.canbot.u05.utils.PathConst;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.view.TimePickerDialog;
import com.canbot.u05.widget.LoadingDialogUtils;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

/**
 * 考勤信息显示界面  to_work_time   off_work_time  值 “09:00”
 */
public class AttendanceSettingTimeActivity extends BaseActivityNoTitle implements View.OnClickListener {

        private static final String TAG = "AttendanceSettingTimeActivity";

        private String[] fileName = new String[]{"gzsz_kq_u05_001.mp3", "gzsz_kq_u05_002.mp3"};

        /**
         * 上班时间
         */
        private String toWorkTime = "09:00";

        /**
         * 下班时间
         */
        private String offWorkTime = "18:00";

        /**
         * 上午下班时间
         */
        private String amOffTime = "";

        /**
         * 下午上班时间
         */
        private String pmWorkTime = "";

        private RelativeLayout rlTime2;

        private Button btnBack;

        private MaterialButton btnSure;

        private Button btnGroupInfo;

        private Button btnWeek1, btnWeek2, btnWeek3, btnWeek4, btnWeek5, btnWeek6, btnWeek7;

        private Button count_2;

        private Button count_4;

        private TextView tvToWorkTime;

        private TextView tvAmOffWorkTime;

        private TextView tvPmToWorkTime;

        private TextView tvOffWorkTime;

        //        private String nonWorkingDay = "一:二:三:四:五:六:日";
        private String nonWorkingDay = "六:日";

        private Dialog dialogLoading;

        private TimePickerDialog timePickerDialog;

        private String timePickerTime;

        private AttendanceSettings attendanceSettings;


        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_attendance_info);
                setViews();
                getDefaultSetting();

                setListener();

                int index = (int) (Math.random() * fileName.length);
                boolean isSuccess = MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.AUDIO_ATTENDANCE_DIR + fileName[index]);
                if (!isSuccess) {
                        ToastTools.newInstance(this).showText(getString(R.string.network_error));
                }

        }

        /**
         * 用户考勤信息显示界面
         */
        private void setViews() {
                rlTime2 = findViewById(R.id.rl_time2);
                tvToWorkTime = findViewById(R.id.am_to_work_time);
                tvAmOffWorkTime = findViewById(R.id.end_time);
                tvPmToWorkTime = findViewById(R.id.work_time_2);
                tvOffWorkTime = findViewById(R.id.end_time_2);

                count_2 = findViewById(R.id.count_2);
                count_4 = findViewById(R.id.count_4);

                btnBack = findViewById(R.id.imageView_back);
                btnGroupInfo = findViewById(R.id.btn_text_group_info);
                btnSure = findViewById(R.id.btn_sure);

                btnWeek1 = findViewById(R.id.week_1);
                btnWeek2 = findViewById(R.id.week_2);
                btnWeek3 = findViewById(R.id.week_3);
                btnWeek4 = findViewById(R.id.week_4);
                btnWeek5 = findViewById(R.id.week_5);
                btnWeek6 = findViewById(R.id.week_6);
                btnWeek7 = findViewById(R.id.week_7);
        }

        private void setListener() {
                btnBack.setOnClickListener(this);
                btnSure.setOnClickListener(this);
                btnGroupInfo.setOnClickListener(this);
//
                count_2.setOnClickListener(this);
                count_4.setOnClickListener(this);
                btnWeek1.setOnClickListener(this);
                btnWeek2.setOnClickListener(this);
                btnWeek3.setOnClickListener(this);
                btnWeek4.setOnClickListener(this);
                btnWeek5.setOnClickListener(this);
                btnWeek6.setOnClickListener(this);
                btnWeek7.setOnClickListener(this);
//
                tvToWorkTime.setOnClickListener(this);
                tvAmOffWorkTime.setOnClickListener(this);
                tvPmToWorkTime.setOnClickListener(this);
                tvOffWorkTime.setOnClickListener(this);
        }

        /**
         * 获取之前设置的时间（网络获取）
         */
        private void getDefaultSetting() {

                attendanceSettings = (AttendanceSettings) getIntent().getSerializableExtra("settings");
                if (attendanceSettings != null) {
                        toWorkTime = attendanceSettings.getToWorkTime();
                        offWorkTime = attendanceSettings.getOffTime();
                        amOffTime = attendanceSettings.getAmOff();
                        pmWorkTime = attendanceSettings.getPmTo();
                        nonWorkingDay = attendanceSettings.getNon_working_day();
                        Logger.e(TAG, "AttendanceSettings = " + attendanceSettings.toString());
                        setText();
                }

//                OkHttpUtils.request("http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755/" + ConstUtils.URL_ATTENDANCE_SET,  new OkHttpUtils.OkHttpCallBack() {
//                        @Override
//                        public void onSuccess(final String result) {
//
//                                Logger.e("save", "onSuccess:" + result);
//                                runOnUiThread(new Runnable() {
//                                        @Override
//                                        public void run() {
//                                                LoadingDialogUtils.closeDialog(dialogLoading);
//                                                JsonResponse jc = JSON.parseObject(result, JsonResponse.class);
//                                                AttendanceSettings o = (AttendanceSettings)jc.getResult();
//
//
//                                        }
//                                });
//                        }
//
//                        @Override
//                        public void onFailure() {
//                                Logger.e("save", "onFailure");
//                                runOnUiThread(new Runnable() {
//                                        @Override
//                                        public void run() {
//                                                LoadingDialogUtils.closeDialog(dialogLoading);
//                                                ToastTools.newInstance(AttendanceSettingTimeActivity.this).showText(AttendanceSettingTimeActivity.this.getString(R.string.network_error));
//                                        }
//                                });
//                        }
//                });
        }

        private void setText() {
                if(!TextUtils.isEmpty(attendanceSettings.getFirstGroupName())){
                        btnGroupInfo.setText(attendanceSettings.getFirstGroupName());
                }

                if (TextUtils.isEmpty(amOffTime) || TextUtils.isEmpty(pmWorkTime)) {  //两次
                        count_4.setSelected(true);
                        rlTime2.setVisibility(View.INVISIBLE);
                }
                else {  //四次
                        count_2.setSelected(true);
                }
                tvToWorkTime.setText(toWorkTime);
                if (TextUtils.isEmpty(amOffTime) || TextUtils.isEmpty(pmWorkTime)) {
                        tvAmOffWorkTime.setText(offWorkTime);
                }
                else {
                        tvAmOffWorkTime.setText(amOffTime);
                        tvPmToWorkTime.setText(pmWorkTime);
                        tvOffWorkTime.setText(offWorkTime);
                }

                if (getString(R.string.attendance_week_text).equals(nonWorkingDay)) {
                        btnWeek1.setSelected(true);
                        btnWeek2.setSelected(true);
                        btnWeek3.setSelected(true);
                        btnWeek4.setSelected(true);
                        btnWeek5.setSelected(true);
                        btnWeek6.setSelected(true);
                        btnWeek7.setSelected(true);
                }
                else {
                        String[] str = nonWorkingDay.split(":");
                        for (int i = 0; i < str.length; i++) {
                                switch (str[i]) {
                                        case "一":
                                                btnWeek1.setSelected(true);
                                                break;
                                        case "二":
                                                btnWeek2.setSelected(true);
                                                break;
                                        case "三":
                                                btnWeek3.setSelected(true);
                                                break;
                                        case "四":
                                                btnWeek4.setSelected(true);
                                                break;
                                        case "五":
                                                btnWeek5.setSelected(true);
                                                break;
                                        case "六":
                                                btnWeek6.setSelected(true);
                                                break;
                                        case "日":
                                                btnWeek7.setSelected(true);
                                                break;
                                }
                        }
                }

        }


        public static final DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm");

        public static final SimpleDateFormat formatDate = new SimpleDateFormat("yyyy/MM/dd", Locale.CHINA);

        /**
         * 提交考勤信息
         */
        private void commitData() {

                HashMap<String, Object> hasMap = new HashMap<>();
                if (!TextUtils.isEmpty(nonWorkingDay)) {
                        if (nonWorkingDay.startsWith(":")) {
                                nonWorkingDay = nonWorkingDay.substring(1, nonWorkingDay.length());
                        }
                        if (nonWorkingDay.endsWith(":")) {
                                nonWorkingDay = nonWorkingDay.substring(0, nonWorkingDay.length() - 1);
                        }
                        Logger.e(TAG, "non_working_day = " + nonWorkingDay);
                }
                toWorkTime = tvToWorkTime.getText().toString().trim();
                String date = formatDate.format(Calendar.getInstance().getTime());
                if (count_2.isSelected()) {
                        //四次
                        Logger.e(TAG, "四次");
                        offWorkTime = tvOffWorkTime.getText().toString().trim();
                        amOffTime = tvAmOffWorkTime.getText().toString().trim();
                        pmWorkTime = tvPmToWorkTime.getText().toString().trim();

                        attendanceSettings.setToWorkTime(toWorkTime);
                        attendanceSettings.setOffTime(offWorkTime);
                        attendanceSettings.setPmTo(pmWorkTime);
                        attendanceSettings.setAmOff(amOffTime);


                        try {
                                //中午下班时间不能早于上班时间
                                if (df.parse(date + " " + amOffTime).getTime() <= df.parse(date + " " + toWorkTime).getTime()) {
                                        ToastTools.newInstance(AttendanceSettingTimeActivity.this).showText(getString(R.string.attendance_time_conflict));
                                        return;
                                }

                                //中午上班时间不能早于上午下班时间哦
                                if (df.parse(date + " " + pmWorkTime).getTime() < df.parse(date + " " + amOffTime).getTime()) {
                                        ;
                                        ToastTools.newInstance(AttendanceSettingTimeActivity.this).showText(getString(R.string.attendance_time_conflict));
                                        return;
                                }

                                //下班时间不能早于中午上班时间哦
                                if (df.parse(date + " " + offWorkTime).getTime() <= df.parse(date + " " + pmWorkTime).getTime()) {
                                        ToastTools.newInstance(AttendanceSettingTimeActivity.this).showText(getString(R.string.attendance_time_conflict));
                                        return;
                                }

                        }
                        catch (ParseException e) {
                                e.printStackTrace();
                        }

                }
                else {
                        //两次
                        Logger.e(TAG, "两次");
                        offWorkTime = tvAmOffWorkTime.getText().toString().trim();

                        attendanceSettings.setToWorkTime(toWorkTime);
                        attendanceSettings.setOffTime(offWorkTime);
                        attendanceSettings.setPmTo("");
                        attendanceSettings.setAmOff("");
                }

                attendanceSettings.setNon_working_day(nonWorkingDay);


                //下班时间不能小于上班时间
                try {

                        if (df.parse(date + " " + offWorkTime).getTime() <= df.parse(date + " " + toWorkTime).getTime()) {
                                ToastTools.newInstance(AttendanceSettingTimeActivity.this).showText(getString(R.string.attendance_time_conflict));
                                return;
                        }
                }
                catch (ParseException e) {
                        e.printStackTrace();
                }


                Logger.e(TAG, "提交数据 时间 =  " + toWorkTime + "  " + amOffTime + "  " + pmWorkTime + "  " + offWorkTime);
                Logger.e(TAG, "非工作日 = " + nonWorkingDay);

                //跳转考勤库管理员界面
                Intent intent = new Intent(AttendanceSettingTimeActivity.this, AttendanceAdminActivity.class);
                intent.putExtra("settings", attendanceSettings);
                startActivity(intent);


//                dialogLoading = LoadingDialogUtils.createLoadingDialog(this, getString(R.string.data_upload));
//                OkHttpUtils.upLoadFile("http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755/" + "settingAttendanceTime", hasMap, new OkHttpUtils.OkHttpCallBack() {
//                        @Override
//                        public void onSuccess(String result) {
//
//                                Logger.e("save", "onSuccess:" + result);
//                                runOnUiThread(new Runnable() {
//                                        @Override
//                                        public void run() {
//                                                LoadingDialogUtils.closeDialog(dialogLoading);
//                                                ToastTools.newInstance(AttendanceSettingTimeActivity.this).showText(AttendanceSettingTimeActivity.this.getString(R.string.upload_complete));
//
//                                                //跳转考勤库管理员界面
//                                                Intent intent = new Intent(AttendanceSettingTimeActivity.this, AttendanceAdminActivity.class);
//                                                intent.putExtra("settings",attendanceSettings);
//                                                startActivity(intent);
//                                        }
//                                });
//                        }
//
//                        @Override
//                        public void onFailure() {
//                                Logger.e("save", "onFailure");
//                                runOnUiThread(new Runnable() {
//                                        @Override
//                                        public void run() {
//                                                LoadingDialogUtils.closeDialog(dialogLoading);
//                                                ToastTools.newInstance(AttendanceSettingTimeActivity.this).showText(AttendanceSettingTimeActivity.this.getString(R.string.network_error));
//                                        }
//                                });
//                        }
//                });
        }

        @Override
        public void onClick(View v) {
                switch (v.getId()) {

                        case R.id.btn_text_group_info:
                                //跳转到人脸库选择
                                Intent intent = new Intent(this, AttendanceGroupActivity.class);
                                intent.putExtra("settings", attendanceSettings);
                                intent.putExtra("fromSettings", true);
                                startActivityForResult(intent, 100);
                                break;
                        case R.id.imageView_back:
                                finish();
                                overridePendingTransition(R.anim.face_zoom_enter, R.anim.face_zoom_exit);
                                break;
                        case R.id.btn_sure:

                                if (btnWeek1.isSelected() && btnWeek2.isSelected() && btnWeek3.isSelected() && btnWeek4.isSelected() && btnWeek5.isSelected() && btnWeek6.isSelected() && btnWeek7.isSelected()) {
                                        ToastTools.newInstance(AttendanceSettingTimeActivity.this).showText(getString(R.string.attendance_empty_work_day_tip));
                                        return;
                                }
                                commitData();
                                break;
                        case R.id.count_2:
                                if (count_2.isSelected()) {
                                        count_2.setSelected(false);
                                        count_4.setSelected(true);
                                        rlTime2.setVisibility(View.INVISIBLE);
                                        //两次和四次时 后边两个时间要显示的不一样
                                        tvAmOffWorkTime.setText(offWorkTime);
                                }
                                else {
                                        count_2.setSelected(true);
                                        count_4.setSelected(false);
                                        rlTime2.setVisibility(View.VISIBLE);
                                        tvAmOffWorkTime.setText(amOffTime);
                                }
                                break;
                        case R.id.count_4:
                                if (count_4.isSelected()) {
                                        count_4.setSelected(false);
                                        count_2.setSelected(true);
                                        rlTime2.setVisibility(View.VISIBLE);
                                        if (TextUtils.isEmpty(amOffTime)) {
                                                amOffTime = "12:00";
                                        }
                                        tvAmOffWorkTime.setText(amOffTime);
                                }
                                else {
                                        count_4.setSelected(true);
                                        count_2.setSelected(false);
                                        rlTime2.setVisibility(View.INVISIBLE);
                                        tvAmOffWorkTime.setText(toWorkTime);
                                }
                                break;
                        case R.id.week_1:
                                if (btnWeek1.isSelected()) {
                                        btnWeek1.setSelected(false);
                                        setNonWorkingDay(false, "一");
                                }
                                else {
                                        btnWeek1.setSelected(true);
                                        setNonWorkingDay(true, "一");
                                }
                                break;
                        case R.id.week_2:
                                if (btnWeek2.isSelected()) {
                                        btnWeek2.setSelected(false);
                                        setNonWorkingDay(false, "二");
                                        //去除
                                }
                                else {
                                        btnWeek2.setSelected(true);
                                        setNonWorkingDay(true, "二");
                                }
                                break;
                        case R.id.week_3:
                                if (btnWeek3.isSelected()) {
                                        btnWeek3.setSelected(false);
                                        setNonWorkingDay(false, "三");
                                }
                                else {
                                        btnWeek3.setSelected(true);
                                        setNonWorkingDay(true, "三");
                                }
                                break;
                        case R.id.week_4:
                                if (btnWeek4.isSelected()) {
                                        btnWeek4.setSelected(false);
                                        setNonWorkingDay(false, "四");
                                }
                                else {
                                        btnWeek4.setSelected(true);
                                        setNonWorkingDay(true, "四");
                                }
                                break;
                        case R.id.week_5:
                                if (btnWeek5.isSelected()) {
                                        btnWeek5.setSelected(false);
                                        setNonWorkingDay(false, "五");
                                }
                                else {
                                        btnWeek5.setSelected(true);
                                        setNonWorkingDay(true, "五");
                                }
                                break;
                        case R.id.week_6:
                                if (btnWeek6.isSelected()) {
                                        btnWeek6.setSelected(false);
                                        setNonWorkingDay(false, "六");
                                }
                                else {
                                        btnWeek6.setSelected(true);
                                        setNonWorkingDay(true, "六");
                                }
                                break;
                        case R.id.week_7:
                                if (btnWeek7.isSelected()) {
                                        btnWeek7.setSelected(false);
                                        setNonWorkingDay(false, "日");
                                        Logger.e(TAG, "R.id.week_7 false 绿色");
                                }
                                else {
                                        btnWeek7.setSelected(true);
                                        setNonWorkingDay(true, "日");
                                        Logger.e(TAG, "R.id.week_7 true 灰色");
                                }
                                break;

                        case R.id.am_to_work_time:
                                String amTo = tvToWorkTime.getText().toString();
                                showTimePicker(getDefaultHour(amTo), getDefaultMin(amTo), tvToWorkTime);

                                break;
                        case R.id.end_time:
                                String amOff = tvAmOffWorkTime.getText().toString();
                                showTimePicker(getDefaultHour(amOff), getDefaultMin(amOff), tvAmOffWorkTime);

                                break;
                        case R.id.work_time_2:
                                String pmTo = tvPmToWorkTime.getText().toString();
                                showTimePicker(getDefaultHour(pmTo), getDefaultMin(pmTo), tvPmToWorkTime);

                                break;
                        case R.id.end_time_2:
                                String pmOff = tvOffWorkTime.getText().toString();
                                showTimePicker(getDefaultHour(pmOff), getDefaultMin(pmOff), tvOffWorkTime);

                                break;
                }
        }

        private void showTimePicker(String hour, String minute, final TextView textView) {

                timePickerDialog = new TimePickerDialog(AttendanceSettingTimeActivity.this);
                timePickerDialog.setTitle("设置时间");
                timePickerDialog.setTime(hour, minute);


                timePickerDialog.setOnPositiveListener(new View.OnClickListener() {


                        @Override
                        public void onClick(View view) {
                                timePickerTime = timePickerDialog.getTime();
                                Logger.e(TAG, "设置时间= " + timePickerTime);
                                timePickerDialog.dismiss();
                                textView.setText(timePickerTime);
                        }
                });
                timePickerDialog.show();
        }

        private String getDefaultHour(String defaultTime) {
                final String[] stramToWorkTime = defaultTime.split(":");
                return stramToWorkTime[0];
        }

        private String getDefaultMin(String defaultTime) {
                final String[] stramToWorkTime = defaultTime.split(":");
                return stramToWorkTime[1];

        }

        private void setNonWorkingDay(boolean flag, String week) {
                nonWorkingDay = nonWorkingDay.trim();
                if (flag) {

                        if (nonWorkingDay.endsWith(":")) {
                                nonWorkingDay = nonWorkingDay + week + ":";
                        }
                        else {
                                nonWorkingDay = nonWorkingDay + ":" + week + ":";
                        }
                }
                else {
                        if (nonWorkingDay.trim().contains(week)) {
                                if (nonWorkingDay.endsWith(week)) {
                                        nonWorkingDay = nonWorkingDay.replace(week, "");
                                }
                                else {
                                        nonWorkingDay = nonWorkingDay.replace(week + ":", "");
                                }
                        }
                }
                Logger.e(TAG, "setNonWorkingDay nonWorkingDay = " + nonWorkingDay + "week " + week);
        }


        private void increaseTime(TextView textView) {

                String originalTime = textView.getText().toString().trim();
                String[] timeSplit = originalTime.split(":");
                String hourString = timeSplit[0];
                String minuteString = timeSplit[1];
                int hour;
                int minute;
                if (hourString.startsWith("0")) {
                        hour = Integer.parseInt(String.valueOf(hourString.charAt(1)));
                }
                else {
                        hour = Integer.parseInt(hourString);
                }
                if (minuteString.startsWith("0")) {
                        minute = Integer.parseInt(String.valueOf(minuteString.charAt(1)));
                }
                else {
                        minute = Integer.parseInt(minuteString);
                }
                if (minute >= 59) {
                        if (hour >= 23) {
                                hour = 0;
                        }
                        else {
                                //hour+1
                                hour = hour + 1;
                        }
                        minute++;
                        minute = 0;
                }
                else {
                        minute++;
                }
                String finalHour = "";
                String finalMinute = "";

                if (hour < 10) {
                        finalHour = "0" + hour;
                }
                else {
                        finalHour = hour + "";
                }
                if (minute < 10) {
                        finalMinute = "0" + minute;
                }
                else {
                        finalMinute = minute + "";
                }
                textView.setText(finalHour + ":" + finalMinute);
        }


        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                super.onActivityResult(requestCode, resultCode, data);
                if (resultCode == RESULT_OK && data != null) {

                        String group = data.getStringExtra("group");
                        List<KqGroup> selectList = JSON.parseArray(group, KqGroup.class);

                        Logger.e(TAG,"选择结果="+selectList.toString());
                        if (!selectList.isEmpty()) {
                                StringBuilder stringBuilder = new StringBuilder();
                                for (int i = 0; i < selectList.size(); i++) {
                                        if (i == selectList.size() - 1) {
                                                stringBuilder.append(selectList.get(i).getGroupId());
                                        }
                                        else {
                                                stringBuilder.append(selectList.get(i).getGroupId()).append(",");
                                        }

                                }
                                attendanceSettings.setGroupId(stringBuilder.toString());
                                if (selectList.size() == 1){
                                        btnGroupInfo.setText(selectList.get(0).getGroupName());
                                        attendanceSettings.setFirstGroupName(selectList.get(0).getGroupName());
                                }
                                else {
                                        btnGroupInfo.setText(selectList.get(0).getGroupName()+"...");
                                        attendanceSettings.setFirstGroupName(selectList.get(0).getGroupName()+"...");
                                }
                        }
                }
        }

                @Override
                protected void onPause () {
                        if (dialogLoading != null && dialogLoading.isShowing()) {
                                LoadingDialogUtils.closeDialog(dialogLoading);
                        }
                        super.onPause();
                }

                @Override
                protected void onDestroy () {
                        if (timePickerDialog != null) {
                                timePickerDialog.dismiss();
                                timePickerDialog = null;
                        }
                        super.onDestroy();

                }
        }
